package com.example.utils;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.apache.commons.beanutils.BeanMap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JSON 工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
public class JsonUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String toJsonString(Object object) {
        try {
//            if (isUnmodifiableMap(object)) {
//                return writeWithClassField((Map<?, ?>) object);
//            }
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException("Failed to serialize object to JSON", e);
        }
    }

    // 判断对象是否是不可修改的 Map
    private static boolean isUnmodifiableMap(Object object) {
        return object instanceof Map && object.getClass().getName().equals("java.util.Collections$UnmodifiableMap");
    }

    // 自定义序列化逻辑，添加 @class 字段
    private static String writeWithClassField(Map<?, ?> map) throws IOException {
        // 使用 StringWriter 和 JsonGenerator 手动构造 JSON
        try (var writer = new java.io.StringWriter();
             var generator = objectMapper.getFactory().createGenerator(writer)) {

            generator.writeStartObject(); // 开始 JSON 对象
            generator.writeStringField("@class", "java.util.Collections$UnmodifiableMap"); // 添加 @class 字段

            // 遍历 Map 的键值对
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                String key = entry.getKey().toString();
                Object value = entry.getValue();

                // 特殊处理 settings.token.id-token-signature-algorithm 字段
                if ("settings.token.id-token-signature-algorithm".equals(key)) {
                    generator.writeFieldName(key); // 写入字段名
                    generator.writeStartArray(); // 开始数组
                    generator.writeString("org.springframework.security.oauth2.jose.jws.SignatureAlgorithm"); // 类名
                    generator.writeString(value.toString()); // 值
                    generator.writeEndArray(); // 结束数组
                } else {
                    generator.writeObjectField(key, value); // 普通字段
                }
            }

            generator.writeEndObject(); // 结束 JSON 对象
            generator.flush();

            return writer.toString();
        }
    }



    public static <T> T parseObject(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        try {
            return objectMapper.readValue(text, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseDefaultTypingObject(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
            return objectMapper.readValue(text, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将map转化为pojo对象
     * @param map
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T  convertValue(Object map, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.convertValue(map,clazz);
    }

    public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
        if (ArrayUtil.isEmpty(bytes)) {
            return null;
        }
        try {
            return objectMapper.readValue(bytes, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(text, typeReference);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Map<String, Object> convertClassToMap(Object bean) {
        // 创建 BeanMap
        BeanMap beanMap = new BeanMap(bean);

        // 创建一个新的 HashMap 来存储结果
        Map<String, Object> resultMap = new HashMap<>();

        // 遍历 BeanMap 并将数据放入 resultMap
        for (Object key : beanMap.keySet()) {
            if (key instanceof String) { // 确保键是字符串类型
                resultMap.put((String) key, beanMap.get(key));
            }
        }

        return resultMap;
    }

    public static <T> List<T> parseArray(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return new ArrayList<>();
        }
        try {
            return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> parseList(Object jsonStrs, Class<T> clazz){
        return JsonUtils.parseArray(JSONObject.toJSONString(jsonStrs), clazz);
    }



}
